<template>
  <u-empty mode="data" v-if="result.data.length <= 0 && result.isEnd"></u-empty>
  <view class="my-group" v-else>
    <view class="list">
      <view class="notices flex flex-ai-c flex-jc-sb" v-for="(item, index) in result.data" :key="index" @click="onClickGroup(item)">
        <view class="noticons2">
          <image :src="item.group_face_url" mode="aspectFill"></image>
          <view class="iconred" v-if="item.im && item.im.unreadCount > 0"></view>
        </view>
        <view class="nottext font-28 color-333">
          {{item.group_name || item.im.groupProfile.name}}<br>
          <text class="font-24 color-999" v-if="item.im">{{item | formatMessage}}</text>
        </view>
        <view class="nitionstxt color-999" v-if="item.im">
          {{item.im.lastMessage.lastTime | formatDate}}
        </view>
      </view>
      
      <view class="loading-status"><u-loadmore :status="result.status" /></view>
    </view>
  </view>
</template>

<script>
import timLogin from '@/utils/timLogin.js' // 导入tim 登录
import formatMessageDate from '@/utils/commen/imTimeFormat.js'
export default {
  data() {
    return {
      result: {
        PageIndex: 1,
        PageSize: 20,
        isEnd: false,
        loading: false,
        status: 'loading',
        data: []
      },
      groupId: ''
    }
  },
  onLoad(option) {
    this.groupId = option.id || ''
    // 登录tim
    if(this.$store.state.isSDKReady) {
      this.getList()
    } else {
      timLogin(() => {
        this.getList()
      })
    }
  },
  filters: {
    formatMessage(data) {
      let text = ''
      // 如果未读数量大于0 则添加进文本
      if(data.im && data.im.unreadCount > 0) {
        text += `[${data.im.unreadCount}条] `
      }
      // 如果发最后一条消息的人有昵称 则添加进文本
      if(data.im.lastMessage.nick) {
        text += `${data.im.lastMessage.nick}: `
      }
      // 最后一条消息内容
      if(data.im.lastMessage.nick) {
        text += `${data.im.lastMessage.messageForShow}`
      }
      return text
    },
    formatDate(data) {
      return data ? formatMessageDate(data * 1000, false) : ''
    }
  },
  methods: {
    // 计算总共有多少页
    pageCount (totalnum,limit){
      return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0
    },
    async getList() {
      let res = this.result
      if (res.loading || res.isEnd) {
        return false;
      }
      res.loading = true;
      this.result = res
      
      try{
        let resData = await this.$api.chat.GetServiceProvidersMemberGroupList({
          pageIndex: res.PageIndex,
          pageSize: res.PageSize,
          iM_Group_Id: this.groupId
        })
        let visitlist = resData.data.list
        // 如果返回数据列表为空，或者当前页数大于总页数代表已经到最后一页了
        if(visitlist.length <= 0 || res.PageIndex >= this.pageCount(resData.data.total, res.PageSize)) {
          res.isEnd = true
          res.status = 'nomore'
        }
        
        if (visitlist.length > 0) {
          res.data = res.data.concat(visitlist)
          res.PageIndex = res.PageIndex + 1
        }
        res.loading = false
        this.result = res
        this.getInfo()
      }catch(e){
        //TODO handle the exception
      }
    },
    getInfo() {
      let list = this.result.data
      let arr = [];
      for(let i in list) {
        arr.push(this.getGroupProfile(list[i]))
      }
      Promise.all(arr).then(data => {
        this.result.data = data
      }).catch(err => { })
    },
    // 获取群资料
    getGroupProfile(data) {
      return new Promise((resolve, reject) => {
        // 获取群资料
        this.tim.getConversationProfile(`GROUP${data.id}`).then(imResponse => {
          let im = imResponse.data.conversation
          this.tim.getUserProfile({
            userIDList: [im.lastMessage.fromAccount]
          }).then(userinfo => {
            im.lastMessage.nick = userinfo.data[0].nick
            data.im = im
            resolve(data)
          }).catch(userinfoError => {
            if(data){
              resolve(data)
            } else {
              reject(userinfoError)
            }
          });
        }).catch(imError => {
          if(data){
            resolve(data)
          } else {
            reject(imError)
          }
        });
      })
      
    },
    // 跳转群聊
    onClickGroup(data) {
      uni.navigateTo({
        url: `/pages_chat/chat/chat?userid=${data.id}&type=GROUP`
      })
    }
  }
}
</script>

<style lang="scss">
page{
  background-color: #F6F6F6;
  height: 100%;
}
.my-group{
  .list{
    padding: 0 24rpx;
    overflow: hidden;
  }
  .notices{
    height: 150rpx;
    background: #FFFFFF;
    box-shadow: 0px 0px 10rpx 0px rgba(0, 0, 0, 0.12);
    border-radius: 10rpx;
    padding: 0rpx 0rpx 0rpx 24rpx;
    margin: 24rpx 0;
    position: relative;
    .noticons{
      width: 90rpx;
      height: 90rpx;
      background: #FFE5DC;
      border-radius: 50%;
      text-align: center;
      line-height: 100rpx;
      position: relative;
    }
    .noticons2{
      width: 90rpx;
      height: 90rpx;
      background: #E0F8CD;
      border-radius: 50%;
      text-align: center;
      line-height: 100rpx;
      position: relative;
      image{
        width: 90rpx;
        height: 90rpx;
        background: #9C9C9C;
        border-radius: 50%;
      }
    }
    // 小红点
    .iconred{
      width: 20rpx;
      height: 20rpx;
      background: #F17124;
      border-radius: 50%;
      position: absolute;
      right: 0;
      top: 8rpx;
    }
    .iconpd{
      margin-left: 18rpx;
      margin-top: 18rpx;
    }
    .nottext{
      text-align: left;
      flex: 1;
      margin-left: 20rpx;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      image{
        width: 45rpx;
        height: 40rpx;
        background: #9C9C9C;
        border-radius: 50%;
        margin-left: 20rpx;
      }
    }
    .nitionstxt{
      position: absolute;
      right: 25rpx;
      top: 40rpx;
      font-size: 22rpx;
    }
  }
  .loading-status{
    padding: 40rpx 0;
  }
}
</style>
